package com.gurun.codes.business.human_body;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.gurun.base.DebounceObservableTransformer;
import com.gurun.base.Logger;
import com.gurun.base.utils.ToastManager;
import com.gurun.codes.R;
import com.gurun.codes.base.BaseAppCompatActivity;
import com.gurun.codes.business.temperature_humidity.TemperatureHumidityActivityContract;
import com.gurun.codes.databinding.ActivityHumanbodyHistoryBinding;
import com.gurun.codes.databinding.ActivityTemperatureHumidityHistoryBinding;
import com.gurun.codes.utils.DateTimeUtils;
import com.gurun.model.bean.AlarmListBean;
import com.gurun.model.bean.human_body.GetHumanInfoResultBean;
import com.gurun.model.bean.temperature_humidity.GetTemperatureHumidityInfoResultBean;
import com.jakewharton.rxbinding2.view.RxView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.functions.Consumer;

/**
 * 人体传感器历史记录
 */
public class HumanBodyHistoryActivity extends BaseAppCompatActivity implements HumanBodyActivityContract.HumanBodyActivityView {
    private static final String ARG_DEVICE_ID = "device_id";

    private ActivityHumanbodyHistoryBinding mBinding;
    private long mDeviceId;
    private ProgressDialog mDialog;
    private GetHumanInfoResultBean mDatas;
    private HumanBodyActivityContract.HumanBodyActivityViewPresenter mPresenter;
    private long mStartTimeSeconds = 0;//第一个数据的秒数
    private ArrayList<Entry> mValues = new ArrayList<Entry>();
    private int mTimeSelectPostion = 1;//1:选中了一天，2：选中了一周，3：选中了一个月
    private int mCurrentTimeFlag = 0;//记录当前请求的是哪个时间的数据,避免重复请求

    public static void startActivity(Context context, long deviceId) {
        Intent intent = new Intent(context, HumanBodyHistoryActivity.class);
        intent.putExtra(ARG_DEVICE_ID, deviceId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_humanbody_history);
        mPresenter = new HumanBodyActivityContract.HumanBodyActivityViewPresenter(this);
        mPresenter.bind(this);
        initView();
        initDatas();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
    }

    @Override
    protected void initView() {
        mBinding.tvOneDay.requestFocus();
        initChart();
    }

    @Override
    protected void initDatas() {
        mDeviceId = getIntent().getLongExtra(ARG_DEVICE_ID, 0);
        mPresenter.getHUmanBodyInfoForChart(mDeviceId, mCurrentTimeFlag);
    }

    @Override
    protected void initEvent() {

        RxView.focusChanges(mBinding.tvOneDay)
                .compose(this.<Boolean>bindToLifecycle())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            mTimeSelectPostion = 1;
                            onTimeFocusChanged();
                        }
                    }
                });

        RxView.focusChanges(mBinding.tvOneWeek)
                .compose(this.<Boolean>bindToLifecycle())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            mTimeSelectPostion = 2;
                            onTimeFocusChanged();
                        }
                    }
                });

        RxView.focusChanges(mBinding.tvOneMonth)
                .compose(this.<Boolean>bindToLifecycle())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            mTimeSelectPostion = 3;
                            onTimeFocusChanged();
                        }
                    }
                });
    }

    private void onTimeFocusChanged() {
        int timeFlag = 0;
        switch (mTimeSelectPostion) {
            case 1:
                mBinding.tvOneDay.setBackgroundResource(R.drawable.shape_background_chart_timeview_sel);
                mBinding.tvOneWeek.setBackgroundResource(R.drawable.background_transparent);
                mBinding.tvOneMonth.setBackgroundResource(R.drawable.background_transparent);
                timeFlag = 0;
                break;
            case 2:
                mBinding.tvOneDay.setBackgroundResource(R.drawable.background_transparent);
                mBinding.tvOneWeek.setBackgroundResource(R.drawable.shape_background_chart_timeview_sel);
                mBinding.tvOneMonth.setBackgroundResource(R.drawable.background_transparent);
                timeFlag = 1;
                break;
            case 3:
                mBinding.tvOneDay.setBackgroundResource(R.drawable.background_transparent);
                mBinding.tvOneWeek.setBackgroundResource(R.drawable.background_transparent);
                mBinding.tvOneMonth.setBackgroundResource(R.drawable.shape_background_chart_timeview_sel);
                timeFlag = 2;
                break;
        }
        if (timeFlag != mCurrentTimeFlag) {
            mValues.clear();
            mBinding.chart.clear();
            mBinding.chart.invalidate();
            mPresenter.getHUmanBodyInfoForChart(mDeviceId, timeFlag);
            mCurrentTimeFlag = timeFlag;
        }
    }

    @Override
    public void onLoading() {
        if (mDialog == null) {
            mDialog = new ProgressDialog(mContext);
            mDialog.setMessage(getString(R.string.common_loading));
        }
        mDialog.show();
    }

    @Override
    public void onLoaded(GetHumanInfoResultBean datas) {
        mDatas = datas;
        parseServerDatas();
        if (mValues.size() > 0) {
            setChartData(mValues);
        }
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(mContext, msg);
    }

    @Override
    public void onComplete() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void resetListDatas() {

    }

    private void parseServerDatas() {
        if (mDatas != null) {
            List<AlarmListBean> alarmListBeans = mDatas.getAlarmList();
            if (alarmListBeans != null && alarmListBeans.size() > 0) {
                List<Float> xList = new ArrayList<>();//x去重

                for (int i = alarmListBeans.size() - 1; i >= 0; i--) {//由于服务器返回的数据是倒序的
                    AlarmListBean item = alarmListBeans.get(i);
                    long time = DateTimeUtils.getLongTime(item.getAlarmTime());
                    if (i == alarmListBeans.size() - 1) {
                        mStartTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(time);
                    }
//                    float x = TimeUnit.MILLISECONDS.toHours(time);//小时为单位
                    float x = TimeUnit.MILLISECONDS.toSeconds(time) - mStartTimeSeconds;
                    float lux = Float.valueOf(item.getLux());

                    if (!xList.contains(x)) {
                        mValues.add(new Entry(x, lux));
                        xList.add(x);
                    }
                }
            }
        }
    }

    //=======================chart==========================

    private void initChart() {
        // no description text
        mBinding.chart.getDescription().setEnabled(false);
        // enable touch gestures
        mBinding.chart.setTouchEnabled(true);
        mBinding.chart.setDragDecelerationFrictionCoef(0.9f);
        // enable scaling and dragging
        mBinding.chart.setDragEnabled(true);
        mBinding.chart.setScaleEnabled(true);
        mBinding.chart.setDrawGridBackground(false);
        mBinding.chart.setHighlightPerDragEnabled(true);
        // set an alternative background color
        mBinding.chart.setBackgroundResource(R.mipmap.bg_humanbodyhistory_bottom);
        mBinding.chart.setViewPortOffsets(0f, 0f, 0f, 0f);
        // get the legend (only possible after setting data)
        Legend l = mBinding.chart.getLegend();
        l.setEnabled(false);
        XAxis xAxis = mBinding.chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM_INSIDE);
        xAxis.setTextSize(10f);
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(false);
        xAxis.setTextColor(getResources().getColor(R.color.color_chart_text_color));
        xAxis.setCenterAxisLabels(true);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {

            private SimpleDateFormat mFormat = new SimpleDateFormat("MM月dd日 HH:mm:ss");

            @Override
            public String getFormattedValue(float value, AxisBase axis) {

//                long millis = TimeUnit.HOURS.toMillis((long) value);//小时为单位
                long value2 = ((long) value) + mStartTimeSeconds;
                long millis = TimeUnit.SECONDS.toMillis(value2);
                return mFormat.format(new Date(millis));
            }
        });
        YAxis leftAxis = mBinding.chart.getAxisLeft();
        leftAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(100f);
        leftAxis.setYOffset(-9f);
        leftAxis.setTextColor(getResources().getColor(R.color.color_chart_text_color));
        leftAxis.setValueFormatter(new IAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return value + "lux";
            }
        });

        YAxis rightAxis = mBinding.chart.getAxisRight();
        rightAxis.setEnabled(false);
    }

    private void setChartData(ArrayList<Entry> values) {
        LineDataSet set1 = new LineDataSet(values, "DataSet 1");
        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
        set1.setColor(Color.parseColor("#8398ff"));
        set1.setValueTextColor(Color.parseColor("#8398ff"));
        set1.setLineWidth(3f);
        set1.setDrawCircles(false);
        set1.setDrawValues(false);
        set1.setDrawFilled(false);
//        set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set1.setFillAlpha(100);
        set1.setFillColor(Color.parseColor("#8398ff"));
        set1.setHighLightColor(Color.parseColor("#8398ff"));
        set1.setDrawCircleHole(false);

        LineData data = new LineData(set1);
        data.setValueTextColor(Color.WHITE);
        data.setValueTextSize(9f);
        mBinding.chart.setData(data);
        mBinding.chart.invalidate();
    }
}
